﻿#region 命名空间

using System;
using System.Configuration;
using System.Web;
using System.Web.Configuration;

#endregion

namespace Sharp.Infrastructure
{
    /// <summary>
    ///     配置文件操作
    /// </summary>
    public class ConfigurationOperator : IDisposable
    {
        private Configuration _config;

        /// <summary>
        ///     配置文件操作
        /// </summary>
        public ConfigurationOperator()
            : this(HttpContext.Current.Request.ApplicationPath)
        {
        }

        /// <summary>
        ///     配置文件操作
        /// </summary>
        /// <param name="path">Web.Config的路径</param>
        public ConfigurationOperator(string path)
        {
            _config = WebConfigurationManager.OpenWebConfiguration(path);
        }

        /// <summary>
        ///     释放
        /// </summary>
        public void Dispose()
        {
            if (_config != null)
            {
                _config.Save();
            }
        }

        /// 节点名称
        /// 节点值
        public void SetAppSetting(string key, string value)
        {
            AppSettingsSection appSetting = (AppSettingsSection) _config.GetSection("appSettings");
            if (appSetting.Settings[key] == null) //如果不存在此节点,则添加
            {
                appSetting.Settings.Add(key, value);
            }
            else //如果存在此节点,则修改
            {
                appSetting.Settings[key].Value = value;
            }
        }

        /// 节点名称
        /// 节点值
        public void SetConnectionString(string key, string connectionString)
        {
            ConnectionStringsSection connectionSetting =
                (ConnectionStringsSection) _config.GetSection("connectionStrings");
            if (connectionSetting.ConnectionStrings[key] == null) //如果不存在此节点,则添加
            {
                ConnectionStringSettings connectionStringSettings = new ConnectionStringSettings(key, connectionString);
                connectionSetting.ConnectionStrings.Add(connectionStringSettings);
            }
            else //如果存在此节点,则修改
            {
                connectionSetting.ConnectionStrings[key].ConnectionString = connectionString;
            }
        }

        /// <summary>
        ///     保存
        /// </summary>
        public void Save()
        {
            _config.Save();
            _config = null;
        }
    }
}